const API_CODE = require("apiCode");

let SAVE_DATA_KEY = require('SaveDataKey');

let SelfSeverApiCall = require("SelfSeverApiCall");

function login(callback) {
  if (cc.sys.platform === cc.sys.WECHAT_GAME) {
    let gameData = LocalData.getItem(SAVE_DATA_KEY, null);
    let data;
    if (gameData) {
      data = {
        code: API_CODE.SUCCEED,
        gameData: gameData,
      };
      console.log("从本地读取到游戏数据", data);
    } else {
      data = {
        code: API_CODE.SUCCEED,
        gameData: GameConfig.defaultPlayerData
      };
    }
    SelfSeverApiCall.getOpenIdFromCode2Session((err, openId) => {
      data.userInfo = {
        id: openId
      };
      callback && callback(null, data);
    });
  } else {
    //web下从本地读取数据
    let res;
    let gameData = LocalData.getItem(SAVE_DATA_KEY, null);
    if (!gameData) {
      res = {
        code: API_CODE.SUCCEED,
        gameData: GameConfig.defaultPlayerData,
        userInfo: {
          id: 'none',
          name: "none",
          avatarUrl: "",
        },
        inviteCount: 0,
      };
    } else {
      res = {
        code: API_CODE.SUCCEED,
        gameData: gameData,
        userInfo: {
          id: 'none',
          name: "none",
          avatarUrl: "",
        },
        inviteCount: 0,
      };
    }
    PlatformUtils.login(() => {
      callback(null, res);
    });
  }
}

/**
 * 邀请报告
 * @param data
 * data.uid    用户uid
 * data.src_uid 源uid
 * data.action  邀请动作
 * @param callback
 */
function inviteReport(data, callback) {
  callback && callback();
}


/**
 * 报告游戏数据
 * @param uid       用户uid
 * @param gameData    游戏数据
 * @param callback
 */
function gameDataReport(uid, gameData, callback) {
  if (!uid)
    return;
  LocalData.setItem(SAVE_DATA_KEY, gameData);
}


/**
 * 报告退出游戏, 同gameDataReport, 仅添加isExitGame, 标记为退出游戏, 服务端可用以判断清除缓存
 * @param uid
 * @param gameData
 * @param callback
 */
function reportGameExit(uid, gameData, callback) {
  if (!uid)
    return;

  LocalData.setItem(SAVE_DATA_KEY, gameData);
}


function resetShareAward(uid, action, callback) {
  callback && callback();
}

module.exports = {
  API_CODE,
  login,
  gameDataReport,
  inviteReport,
  reportGameExit,
  resetShareAward
};